package com.gdk.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.gdk.service.TicketOrderService;
import com.gdk.utils.HUtil;
import com.gdk.utils.XVDateUtils;
import com.google.gson.Gson;

import net.sf.json.JSONArray;

/**
 * 订单Controller
 * @author xuwei
 * time 2019/02/22 10:57
 * */


@Controller
public class TicketOrderController {
	
	@Autowired
	TicketOrderService ticketOrderService;
	
	
	/**
	 * 查询所有订单
	 * @author xuwei
	 * time 2019/02/22 10:58
	 * */
	@RequestMapping("/findAllOrder.do")
	public String findAllOrder(HttpServletRequest request) {
		

		List<Map<String, Object>> findAllOrder = ticketOrderService.doFindAllOrder();
		request.setAttribute("findAllOrder",findAllOrder);
		return "jsp/order_manage";		
	}
	/**
	 * 动态查询订单
	 * @author xuwei
	 * time 2019/02/22 21:08
	 * */

	@RequestMapping("/findAllOrderPaging.do")
	public String findAllOrderPaging(@RequestParam Map<String,Object> map,ModelMap model,HttpServletRequest request,HttpServletResponse response) {
		System.out.println("订单Map : "+map);
		int page_num = 20;
		int number = 1;
		int size = 0;
		List<Map<String, Object>> AllOrder = null;
	
	
		if(!("".equals(map.get("page_num")) || map.get("page_num") == null)) {
			page_num = Integer.parseInt(map.get("page_num").toString());
		}
		
		map.put("page_num", page_num);
	//	System.out.println("所有订单查询"+map);
		if(map.get("number") != null && !"".equals(map.get("number")) ) {
			number = Integer.valueOf(map.get("number").toString());
		}
		int pageNum = number;
	//	System.out.println("pageNum  :  "+pageNum);
		map.remove("number");
		//map.put("number", number);
	//	System.out.println("map  : "+map);
		
		String nnnm = page_num+"";
	//	System.out.println("nnnm  :"+nnnm);
		double page_float = Double.parseDouble(nnnm);
	//	System.out.println("page_float  :"+page_float);
		int itemCount =  ticketOrderService.doFindAllOrderPaging(map).size();
		
		//计算实际收费
		double order_amount_total = 0.00;
		for (Map<String, Object> map2 : ticketOrderService.doFindAllOrderPaging(map)) {
			if((int)map2.get("order_status") >0) {
				order_amount_total = order_amount_total+(double) map2.get("order_amount_total");
			}
		
		}
		
		DecimalFormat df1 = new DecimalFormat("#.###");
		//System.out.println("allMoneyCount===="+ df1.format(allMoneyCount) );
		
		order_amount_total = Double.parseDouble(df1.format(order_amount_total));
		request.setAttribute("order_amount_total", order_amount_total);
		
		map.put("allOrderItem",itemCount);
		
		//size = (int) Math.ceil(ticketOrderService.doSelectAllOrder(map).size()/(pageNum+0.0));
		size = (int) Math.ceil(itemCount/page_float);
		//size = (int) Math.ceil(ticketOrderService.doSelectAllOrder(map).size()/10.0f);
		//System.out.println("分页数量  : "+size);
		if (size == 0) {
	
			request.setAttribute("msg", "没符合的数据");
			return "jsp/order/order_manage";
		}
		if (number == 1) {
			map.put("number", 0);
		} else {
			map.put("number",(number-1)*page_num);
		}
//				System.err.println("分页数据    :  "+map);

		//分页所有订单
		AllOrder = ticketOrderService.doFindAllOrderPaging(map);
		
		
		for (Map<String, Object> map2 : AllOrder) {
			String o_endtime = map2.get("o_endtime").toString();
			
			//System.out.println("o_endtime : "+o_endtime);
			//订单到期时间
			int toMillis = XVDateUtils.stringDateToMillis(o_endtime);
			//System.out.println("toMillis : "+toMillis);
			//String format = XVDateUtils.MillisFormat(toMillis);
			//System.out.println("format : "+format);
			int now_time = XVDateUtils.getCurrenTimeMillis();
			if(toMillis < now_time) {
				//已到期
				map2.put("dq_time_flag", "abnormal");

			}else {
				//未过期
				map2.put("dq_time_flag", "normal");
			}
		}
		
		//System.out.println("AllOrder  : "+AllOrder);
		//List<Map<String, Object>> allOrder = ticketOrderService.doSelectAllOrder(map);
		model.addAttribute("AllOrder", AllOrder);
		//所有类型
		map.put("number", pageNum);
		map.put("sumNumber", size);
		model.addAttribute("page", map);
//		System.out.println("page_map map内含  :   "+map);
		
		
		
		return "jsp/order/order_manage";
	}
	/**
	 * 修改订单状态
	 * @author xuwei
	 * time 2019/02/23 16:58
	 * */
	@ResponseBody
	@RequestMapping("/updateOrderStatus.do")
	public int updateOrderStatus(@RequestParam Map<String,Object> map,HttpServletRequest request) {
		System.out.println(" map : "+map);
		return ticketOrderService.doUpdateOrderStatus(map);		
	}
	/**
	 * 修改订单状态
	 * @author xuwei
	 * time 2019/02/23 16:58
	 * */
	@RequestMapping("/findAllOrderByFXOne.do")
	public String findAllOrderByFXOne(@RequestParam Map<String,Object> map,HttpServletRequest request) {
		System.out.println(" map : "+map);
		List<Map<String, Object>> findAllOrderByFXOne = ticketOrderService.doFindAllOrderByFXOne(map);
		request.setAttribute("findAllOrderByFXOne",findAllOrderByFXOne);
		return "jsp/user_fx_one_order";
	}
	/**
	 * 查看相关联的核销码  
	 * @author xuwei
	 * time 2019/03/13 10:51
	 * */
	@RequestMapping("/findHXCodeByOrder.do")
	public String findHXCodeByOrder(@RequestParam Map<String,Object> map,HttpServletRequest request) {
		System.out.println(" map : "+map);
		List<Map<String, Object>> findHXCodeByOrder = ticketOrderService.doFindHXCodeByOrder(map);
		request.setAttribute("findHXCodeByOrder",findHXCodeByOrder);
		//查询核销码是否过期
		String o_endtime = findHXCodeByOrder.get(0).get("o_endtime").toString();
		
		System.out.println("o_endtime : "+o_endtime);
		//订单到期时间
		int toMillis = XVDateUtils.stringDateToMillis(o_endtime);
		//System.out.println("toMillis : "+toMillis);
		//String format = XVDateUtils.MillisFormat(toMillis);
		//System.out.println("format : "+format);
		int now_time = XVDateUtils.getCurrenTimeMillis();
		if(toMillis < now_time) {
			//已到期
			request.setAttribute("dq_time_flag", "abnormal");

		}else {
			//未过期
			request.setAttribute("dq_time_flag", "normal");
		}
		
		
		
		
		return "jsp/order/order_hx_code";
	}
	/**
	 * 接口
	 *查询所有核销码  
	 * @author xuwei
	 * time 2019/03/13 14:08
	 * */
	@ResponseBody
	@RequestMapping(value="/findAllHXCode.do",produces = "application/json;charset=UTF-8")
	public String findAllHXCode(@RequestParam Map<String,Object> map, HttpServletRequest request,HttpServletResponse response) {
	
		List<Map<String, Object>> doFindAllHXCode = ticketOrderService.doFindAllHXCode(map);
	//	System.out.println(" doFindAllHXCode : "+doFindAllHXCode);
		//request.setAttribute("doFindAllHXCode",doFindAllHXCode);

		for(int i=0;i < doFindAllHXCode.size();i++) {
			Map<String, Object> map2 = doFindAllHXCode.get(i);
			if(map2.get("showcodecreatetime")!=null) {
				String showcodecreatetime = map2.get("showcodecreatetime").toString();
				map2.put("showcodecreatetime", showcodecreatetime);				
			}
			if(map2.get("showusetime")!=null) {
				String showusetime = map2.get("showusetime").toString();
				map2.put("showusetime", showusetime);
			}
			if(map2.get("showendtime")!=null) {
				String showendtime = map2.get("showendtime").toString();
				map2.put("showendtime", showendtime);
			}
			doFindAllHXCode.set(i, map2);
		}
		
		
		Gson gson = new Gson();
		String allHXCode = gson.toJson(doFindAllHXCode);
		
		return allHXCode;
	}
	/**
	 * 接口
	 *查询核销码信息  
	 * @author xuwei
	 * time 2019/03/13 17:34
	 * */
	@ResponseBody
	@RequestMapping(value="/findHXCodeByCode.do",produces = "application/json;charset=UTF-8")
	public String findHXCodeByCode(@RequestParam Map<String,Object> map, HttpServletRequest request) {
		List<Map<String,Object>> findHXCodeByCode = ticketOrderService.doFindHXCodeByCode(map);
		for(int i=0;i < findHXCodeByCode.size();i++) {
			Map<String, Object> map2 = findHXCodeByCode.get(i);
			if(map2.get("showcodecreatetime")!=null) {
				String showcodecreatetime = map2.get("showcodecreatetime").toString();
				map2.put("showcodecreatetime", showcodecreatetime);				
			}
			
			if(map2.get("showusetime")!=null) {
				String showusetime = map2.get("showusetime").toString();
				map2.put("showusetime", showusetime);
			}
			if(map2.get("showendtime")!=null) {
				String showendtime = map2.get("showendtime").toString();
				map2.put("showendtime", showendtime);
			}
			findHXCodeByCode.set(i, map2);
		}
		
		Gson gson = new Gson();
		String allHXCode = gson.toJson(findHXCodeByCode);
		return allHXCode;
	}
	/**
	 *修改核销码状态  
	 * @author xuwei
	 * time 2019/03/13 17:44
	 * */
	@ResponseBody
	@RequestMapping("/updateHXCodeByCode.do")
	public int updateHXCodeByCode(@RequestParam Map<String,Object> map, HttpServletRequest request) {
		
		map.put("oh_status", 1);
		int updateHXCodeStatus = ticketOrderService.doUpdateHXCodeStatus(map);
		//查询该订单有无其他码,全部使用改订单状态
		//使用oh_id查询出订单号
		//再使用订单号查询有无其他未核销的码
		//有-->待使用    无-->订单完成(佣金分配?)
		
		Map<String, Object> HXCode = ticketOrderService.selectHXCodeByID(map);
		
		List<Map<String, Object>> allHXCodeByOrderAndCodeStatus = ticketOrderService.selectAllHXCodeByOrderAndCodeStatus(HUtil.putInMap("o_id",HXCode.get("o_id"),"oh_status",0));
		if(allHXCodeByOrderAndCodeStatus.size() > 0) {
			//指定存在未核销的码,不处理
		}else {
			//指定订单的码已全部核销,更改订单状态
			ticketOrderService.doUpdateOrderStatus(HUtil.putInMap("id",HXCode.get("o_id"),"order_status",4));
		}
		
		return updateHXCodeStatus;
		
	}
	/**
	 * 接口
	 *查询指定商户的所有订单
	 * @author xuwei
	 * time 2019/03/14 13:56
	 * */
	@ResponseBody
	@RequestMapping(value="/findAllOrderByShop.do",produces = "application/json;charset=UTF-8")
	public String findAllOrderByShop(@RequestParam Map<String,Object> map, HttpServletRequest request) {
		
		List<Map<String, Object>> findAllOrderByShop = ticketOrderService.doFindAllOrderByShop(map);
		//System.out.println("findAllOrderByShop : "+findAllOrderByShop);
		for (int i = 0; i < findAllOrderByShop.size(); i++) {
			Map<String,Object> map2 = findAllOrderByShop.get(i);
			
			if(map2.get("created_at") != null) {
				String created_at = map2.get("created_at").toString();
				map2.put("created_at", created_at);
			}
			if(map2.get("pay_time") != null) {
				String pay_time = map2.get("pay_time").toString();
				map2.put("pay_time", pay_time);
			}
			findAllOrderByShop.set(i, map2);
		}
	
		Gson gson = new Gson();
		String json = gson.toJson(findAllOrderByShop);
		//System.out.println("jsonByShop : "+json);
		return json;
		
	}
	
	//扫码核销
	@ResponseBody
	@RequestMapping(value="/verify_QRCode.do",method={RequestMethod.POST},produces = "text/html;charset=utf-8")
	public String verify_QRCode(@RequestParam Map<String,Object> map,HttpServletRequest request,HttpServletResponse response)  {
		response.setHeader("Content-Type","text/plain;charset=UTF-8");		
		System.out.println("map : "+map);
		
		String result = "code=0000";
		StringBuffer data_str = new StringBuffer();
		// 通过字节流方法获取表单数据
		try {
			ServletInputStream sis = request.getInputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while( (len= sis.read(b)) != -1) {
				//System.out.println(new String(b, "UTF-8"));
				data_str.append(new String(b, "UTF-8"));
			}
			sis.close();

			String qr_data =data_str.toString();
			System.out.println("qr_data  : "+qr_data);
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String[] split = qr_data.split("&&");
			String QRCode_str =  split[0].trim();
			String device_str =  split[1].trim();
			System.out.println("QRCode_str : "+QRCode_str);
			System.out.println("device_str : "+device_str);
			String[] qr_sp = QRCode_str.split("=");
			String QRCode = qr_sp[1].trim();
			System.out.println("QRCode : "+QRCode);
			
			Map<String, Object> hxCodeByCode = ticketOrderService.selectHXCodeByCode(HUtil.putInMap("hx_code",QRCode));
			
			if(hxCodeByCode == null ) {
				System.out.println("核销码 : "+QRCode+"不存在,请核实");
				return "code=1111";
			}
			
			
			
			int oh_status = Integer.valueOf(hxCodeByCode.get("oh_status").toString());
			if(oh_status == 1) {
				System.out.println("核销码 : "+QRCode+"已被使用,无法再次使用");
				return "code=2222";
			}
			
			String o_endtime = hxCodeByCode.get("o_endtime").toString();
			//订单到期时间
			int toMillis = XVDateUtils.stringDateToMillis(o_endtime);
			//System.out.println("toMillis : "+toMillis);
			//String format = XVDateUtils.MillisFormat(toMillis);
			//System.out.println("format : "+format);
			int now_time = XVDateUtils.getCurrenTimeMillis();
			if(toMillis < now_time) {
				System.out.println("核销码 : "+QRCode+"已过期");
				return "code=3333";
			}
			
			
			//修改核销码状态 
			int hxCodeStatusByCode = ticketOrderService.updateHXCodeStatusByCode(HUtil.putInMap("oh_status",1,"oh_type",1,"oh_hexiaoma",QRCode));
			
			if(hxCodeStatusByCode == 1 ) {
				Map<String, Object> HXCode = ticketOrderService.selectHXCodeByHXCode(HUtil.putInMap("oh_hexiaoma",QRCode));
				
				List<Map<String, Object>> allHXCodeByOrderAndCodeStatus = ticketOrderService.selectAllHXCodeByOrderAndCodeStatus(HUtil.putInMap("o_id",HXCode.get("o_id"),"oh_status",0));
				if(allHXCodeByOrderAndCodeStatus.size() > 0) {
					//指定存在未核销的码,不处理
				}else {
					//指定订单的码已全部核销,更改订单状态
					ticketOrderService.doUpdateOrderStatus(HUtil.putInMap("id",HXCode.get("o_id"),"order_status",4));
				}
				return "code=0000";
			}else {
				System.out.println("核销码 : "+QRCode+"核销失败");
				return "code=4444";
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("核销异常");
			return "code=5555";
		}
	}
	
	
	
	
}
